package com.bree.erp.service.stateless;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Address;
import com.bree.erp.entity.PhoneType;
import com.bree.erp.entity.Warehouse;
import com.bree.erp.service.WarehouseService;

@Stateless
public class WarehouseServiceBean implements WarehouseService {

	@PersistenceContext()
	private EntityManager em;

	public WarehouseServiceBean() {
	}
	
	public WarehouseServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public Warehouse create(String code, String name) {
		
		Warehouse wh = new Warehouse();
		
		wh.setId(code);
		wh.setName(name);
		
		em.persist(wh);
		
		return wh;
	}

	@Override
	public Warehouse read(String code) {
		return em.find(Warehouse.class, code);
	}

	@Override
	public Warehouse update(String code, String name) {
		
		Warehouse wh = read(code);
		wh.setName(name);
		
		return wh;
	}

	@Override
	public Warehouse update(String code, Address address) {

		Warehouse wh = read(code);
		wh.setAddress(address);
		
		return wh;
	}

	@Override
	public Warehouse update(String code, PhoneType type, String phoneDetail) {

		Warehouse wh = read(code);
		
		Map<PhoneType, String> phones = wh.getPhoneNumbers();
		if(phones == null) {
			phones = new HashMap<PhoneType, String>();
			wh.setPhoneNumbers(phones);
		}
		
		phones.put(type, phoneDetail);
		
		return wh;
	}

	@Override
	public void delete(String code) {

		Warehouse wh = read(code);
		
		em.remove(wh);
	}

	@Override
	public List<Warehouse> list() {
		TypedQuery<Warehouse> query = em.createNamedQuery(Warehouse.QUERY_SELECT_ALL_WAREHOUSE, Warehouse.class);
		return query.getResultList();
	}

}
